import { computed, reactive, ref, watch } from "vue";
import { defineStore } from "pinia";
import tools from "@/utils/tools";

export const useAppStore = defineStore("app", () => {
  // 主题
  const theme = ref("default");

  // 是否滚动到页面中间
  const isScrollMiddle = ref<boolean>(false);
  // 是否滚动到页面底部
  const isScrollBottom = ref<boolean>(false);

  // 断点
  const breakpoints = ref({
    xxl: 1400,
    xl: 1200,
    lg: 992,
    md: 768,
    sm: 576,
    xs: 0,
  });
  // 判断屏幕大小，断点之后分为：xxl、xl、lg、md、sm、xs几种，具体查看media.scss
  const deviceScreenSize = ref<string>(tools.isMobile() ? "sm" : "xl");
  // 是否为手机端
  const deviceMobileFlag = computed(() =>
    ["xs", "sm", "md", "lg"].includes(deviceScreenSize.value)
  );
  const deviceInnerWidth = ref(0);

  // 侧边栏
  const sideBar = reactive({
    isCollapse: ref(false),
    handleCollapse: () => {
      sideBar.isCollapse = !sideBar.isCollapse;
    },
  });

  // meta 数据
  const meta = reactive({
    metaInfo: ref({
      title: "",
      keywords: "",
      description: "",
    }),
    setMeta: (metaInfo) => {
      meta.metaInfo = metaInfo;
    },
  });

  return {
    theme,
    isScrollMiddle,
    isScrollBottom,
    deviceScreenSize,
    sideBar,
    meta,
    deviceMobileFlag,
    deviceInnerWidth,
    breakpoints,
  };
});

// 监听宽度变化
export const handleResize = () => {
  try {
    tools.debounce(
      () => {
        const innerWidth = window.innerWidth;
        useAppStore().deviceInnerWidth = innerWidth;
        for (let key in useAppStore().breakpoints) {
          if (innerWidth < useAppStore().breakpoints[key])
            useAppStore().deviceScreenSize = key;
        }
        // 手机端
        useAppStore().deviceScreenSize = tools.isMobile()
          ? "md"
          : useAppStore().deviceScreenSize;
      },
      1000,
      true
    )();
  } catch (error) {
    console.error(error);
  }
};
